package com.zzw.spring.aop;

import com.zzw.spring.aop.service.SystemBootAddon;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.OrderComparator;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zzw
 * @see
 * @since 2018/3/2
 */
@Component
public class SystemBootManager implements ApplicationListener<ContextRefreshedEvent> {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private List<SystemBootAddon> systemBootAddons = new ArrayList<>();
    private boolean hasRunOnce = false;

    public List<SystemBootAddon> getSystemBootAddons() {
        return systemBootAddons;
    }

    @Autowired
    public void setSystemBootAddons(List<SystemBootAddon> systemBootAddons){
        Assert.assertNotNull(systemBootAddons);
        OrderComparator.sort(systemBootAddons);
        this.systemBootAddons = systemBootAddons;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(!hasRunOnce){
            for(SystemBootAddon systemBootAddon:systemBootAddons){
                systemBootAddon.onReady();
                logger.info(systemBootAddon.getClass().getCanonicalName());
            }
            hasRunOnce = true;
        }
        else {
            logger.info("已经执行过");
        }
    }
}
